//
//  tab_Catalog.m
//  VivaModa
//
//  Created by Owly MacBook on 01.02.13.
//  Copyright (c) 2013 private_busines. All rights reserved.
//

#import "tab_Catalog.h"
#import "catalog_cell.h"


#define SectionHeaderHeight 50


@interface tab_Catalog ()

@end

@implementation tab_Catalog
@synthesize list_matherial;
@synthesize list_ornamentetion;
@synthesize list_stock;
@synthesize tableView;
@synthesize ornament_control;
@synthesize infoData;

int group_prod;/// 1 - украшения, 2 - подбор, 3 - акции



NSString *nameSelectedCategories;
NSString *podbor_key;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)runSQL_ornamentation{
    self.list_ornamentetion = [SQLiteAccess selectManyRowsWithSQL:@"SELECT * FROM list_ornamentation"];
}

- (void)runSQL_matherial{
    self.list_matherial = [SQLiteAccess selectManyRowsWithSQL:@"SELECT * FROM list_matherial"];
}

- (void)runSQL_stock{
    self.list_stock = [SQLiteAccess selectManyRowsWithSQL:@"SELECT * FROM list_stock"];
}

-(void)runSQLList_data{
    [self runSQL_matherial];
    [self runSQL_ornamentation];
    [self runSQL_stock];
}







- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    self.view.backgroundColor = [Singleton sharedMySingleton].backgroundTableView;
    
    [self runSQLList_data];
    [self.tableView setBackgroundView:nil];
    [self.tableView setBackgroundView:[[UIView alloc] init]];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    [self setNaviganionImg];
    [self setNavigationTitle];
    //[self.navigationItem setTitle:@"Каталог Украшений"];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] init];
    barButton.title = @"Каталог";
    self.navigationItem.backBarButtonItem = barButton;
    
    [UserDefaults setObject:[NSDictionary dictionaryWithObjects:@[@"NO",@"0"] forKeys:@[@"AutoSwitch",@"id_categories"]] forKey:@"automaticSwichID"];
    [self parseCategories];
    
    
    
}





- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self ShowStockCategories]?3:2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:{
            return [self.list_ornamentetion count];
            break;}
        case 1:{
            return [self ShowStockCategories]?[self.list_stock count]:[self.list_matherial count];
            break;}
        case 2:{
            return [self.list_matherial count];
            break;}
            
        default:
            break;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"catalog_identifi";
    
    
   
    catalog_cell *cell = nil;
    cell = (catalog_cell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell)
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"catalog_cell" owner:nil options:nil];
        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[catalog_cell class]])
            {
                cell = (catalog_cell *)currentObject;
                break;
            }
        }
    }
    
    switch (indexPath.section) {
        case 0:{
            cell.name_catalog.text = [[self.list_ornamentetion objectAtIndex:indexPath.row] objectForKey:@"name"];
            break;}
        case 1:{
            cell.name_catalog.text = [[[self ShowStockCategories]?self.list_stock:self.list_matherial objectAtIndex:indexPath.row] objectForKey:@"name"];
            break;}
        case 2:{
            cell.name_catalog.text = [[self.list_matherial objectAtIndex:indexPath.row] objectForKey:@"name"];
            break;}
            
        default:
            break;
    }

    [cell.name_catalog setFont:[UIFont fontWithName:@"Century Gothic" size:17.0]];
    [cell.name_catalog setTextColor:[UIColor colorWithRed:242.0/255.0 green:240.0/255.0 blue:234.0/255.0 alpha:1]];
    [cell.name_catalog setHighlightedTextColor:[UIColor purpleColor]];
    
    UIView *selectedView = [[UIView alloc] init];
    selectedView.backgroundColor = [UIColor clearColor];
    cell.selectedBackgroundView = selectedView;
    
    return cell;
}


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
 
    int id_cat;
    
    switch (indexPath.section) {
        case 0:{
            group_prod = 1;
            nameSelectedCategories= [[self.list_ornamentetion objectAtIndex:indexPath.row] objectForKey:@"name"];
            id_cat = [[[self.list_ornamentetion objectAtIndex:indexPath.row] objectForKey:@"categories_id"] integerValue];
            break;}
        case 1:{
            nameSelectedCategories = [[[self ShowStockCategories]?self.list_stock:self.list_matherial objectAtIndex:indexPath.row] objectForKey:@"name"];
            
            if (![self ShowStockCategories]) {
                podbor_key = [[self.list_matherial objectAtIndex:indexPath.row] objectForKey:@"search_key"];
            }
            
            id_cat = [[[[self ShowStockCategories]?self.list_stock:self.list_matherial objectAtIndex:indexPath.row] objectForKey:@"categories_id"] integerValue];
            group_prod = [self ShowStockCategories]?3:2;

            break;}
        case 2:{
            nameSelectedCategories = [[self.list_matherial objectAtIndex:indexPath.row] objectForKey:@"name"];
            podbor_key = [[self.list_matherial objectAtIndex:indexPath.row] objectForKey:@"search_key"];
            group_prod = 2;
            break;}
            
        default:
            break;
    }


    if ([[UserDefaults objectForKey:@"SuccsesUpdateCategories"] isEqualToString:@"NO"]) {
        if ([self InternetConnection]) {
            [self parseCategories];
        }else{
            if (group_prod==1) {
                [self switchOrnamentationView:id_cat];
            }else{
                if (group_prod==2) {
                    [self switchOrnamentationView:-1];
                }
            }
             
    
        }
    }else{
        if (group_prod==1) {
            [self switchOrnamentationView:id_cat];
        }else{
            if (group_prod==2) {
                [self switchOrnamentationView:-1];
            }
        };
    }
}



-(void)switchOrnamentationView:(int)id_categories{

    if (!ornament_control) {
        ornament_control = [[Ornamentation_controller alloc] initWithNibName:@"Ornamentation_controller" bundle:nil];
    }
    ornament_control.name_categories = nameSelectedCategories;
    if (group_prod==1) {
        ornament_control.type_categoria = ornament;
        ornament_control.id_categories = id_categories;
    }else{
        if (group_prod==2) {
            ornament_control.type_categoria = ornament_podbor;
            ornament_control.key_podbor = podbor_key;
        }else{ornament_control.type_categoria = ornament_stock;
        }

    }
    
    ornament_control.needReload = YES;
    [self.navigationController pushViewController:ornament_control animated:YES];
}





- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return SectionHeaderHeight;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
        
    // Create label with section title
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(0, 10, 315, 44);
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = UITextAlignmentCenter;
    
    [label setFont:[UIFont fontWithName:@"Esenin script One" size:35.0]];
    [label setTextColor:[UIColor colorWithRed:29.0/255.0 green:38.0/255.0 blue:39.0/255.0 alpha:1]];
    
    
    UIImageView *left_img = [[UIImageView alloc]init];
    left_img.image = [UIImage imageNamed:@"left_line"];
    
    UIImageView *right_img = [[UIImageView alloc]init];
    right_img.image = [UIImage imageNamed:@"right_line"];
    
    switch (section) {
        case 0:{
            label.text = @"Украшения";
            left_img.frame = CGRectMake(8, 34, 85, 2);
            right_img.frame = CGRectMake(227, 34, 85, 2);
            break;}
        case 1:{
            ////////////////// Акций не будет
            left_img.frame = CGRectMake(8, 34, 42, 2);
            right_img.frame = CGRectMake(270, 34, 42, 2);
            label.text = [self ShowStockCategories]?@"Акции":@"Подбор Украшений";
            break;}
        case 2:{
            label.text = @"Подбор Украшений";
            break;}
        default:
            break;
    }
    

    
    
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, SectionHeaderHeight)];
    [view addSubview:left_img];
    [view addSubview:right_img];
    [view addSubview:label];
    return view;
}


- (BOOL)ShowStockCategories{
    return NO;
}



#pragma mark Dejal activity

- (void)displayActivityView
{
    //[self removeActivityView];
    
    if ([DejalActivityView isActive]) {
        return;
    }
    
    UIView *viewToUse = self.tabBarController.tabBar.superview;
    [DejalBezelActivityView activityViewForView:viewToUse];
    [DejalActivityView currentActivityView].showNetworkActivityIndicator = YES;
    [DejalActivityView currentActivityView].activityLabel.text = @"Синхронизация";
    //[self performSelector:@selector(removeActivityView) withObject:nil afterDelay:3.0];
}

- (void)removeActivityView;
{
    [DejalBezelActivityView removeViewAnimated:YES];
    [[self class] cancelPreviousPerformRequestsWithTarget:self];
}

#pragma mark 



-(void)parseCategories{
    NSURL* url = [NSURL URLWithString:@"http://moda.viva-viva.ru/mobile/categories.php"];     NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [self displayActivityView];
    if (connection) {
        self.infoData = [NSMutableData data];
    }
}




- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    //[self removeActivityView];
    [self showNoInternetAlert];
}



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [infoData appendData:data];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{
    NSString *result = [[NSString alloc] initWithData:infoData encoding:NSUTF8StringEncoding];
    //NSLog(@"result = %@", result);
    
    
    [self parseJSON:infoData];
    
}


#pragma mark parse JSON result

-(void)parseJSON:(NSData*)data{
    NSDictionary *temtData;
    NSMutableArray *tempArrayData = [[NSMutableArray alloc] initWithCapacity:1];
    
    
    NSError* error;
    
    NSDictionary* json = [NSJSONSerialization
                          
                          JSONObjectWithData:data
                          
                          options:kNilOptions
                          
                          error:&error];
    
    NSString* requestResultAutorization = [json objectForKey:@"success"];
    
    NSArray * array = [json objectForKey:@"message"];
    
    
    
    //NSLog(@"json = %@",json);
    
    
    
    if ([requestResultAutorization integerValue]==1) {
        for (int i=0; i< [array count];i++) {
            //NSLog(@"categories_name = %@  %@",[[array objectAtIndex:i] objectForKey:@"categories_name"],[[array objectAtIndex:i] objectForKey:@"categories_id"]);
        }
        
        [SQLiteAccess deleteWithSQL:@"DELETE FROM list_ornamentation"];
        for (int i=0; i< [array count];i++) {
            [SQLiteAccess insertWithSQL:[NSString stringWithFormat:@"INSERT INTO list_ornamentation(categories_id,name) VALUES(%i,'%@')",[[[array objectAtIndex:i] objectForKey:@"categories_id"] integerValue],[[array objectAtIndex:i] objectForKey:@"categories_name"]]];
            ;
            temtData = [NSDictionary dictionaryWithObjects:@[[NSString stringWithFormat:@"%@",[[array objectAtIndex:i] objectForKey:@"categories_id"]],[NSString stringWithFormat:@"%@",[[array objectAtIndex:i] objectForKey:@"categories_name"]]] forKeys:@[@"categories_id",@"name"]];
            [tempArrayData addObject:temtData];
        }
        [UserDefaults setObject:@"YES" forKey:@"SuccsesUpdateCategories"];
        self.list_ornamentetion = tempArrayData;
        [self.tableView reloadData];
        
    }else{
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Уведомление" message:@"Ошибка синхронизации" delegate:nil cancelButtonTitle:@"Закрыть" otherButtonTitles:nil];
        [alert show];
        
    }
    
    
    
    [self removeActivityView];
    
    
    //[self performSelector:@selector(removeActivityView) withObject:nil afterDelay:0.7];
     
}


- (void)showNoInternetAlert
{
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка Internet соединения" message:@"Для работы с магазином необходимо подключение к сети Internet. Пожалуйста, проверте подключение к сети и повторите попытку."];
    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        [UserDefaults setObject:@"NO" forKey:@"SuccsesUpdateCategories"];
        [self removeActivityView];
    }];
    //[alert setDestructiveButtonWithTitle:@"Повторить" block:nil];
    [alert addButtonWithTitle:@"Повторить " block:^{
        //[self displayActivityView];
        [self performSelector:@selector(parseCategories) withObject:nil afterDelay:1.0];
        //[self parseCategories];
    }];
  [alert show];
}


-(BOOL)InternetConnection{
    internetReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [internetReach currentReachabilityStatus];
    if (netStatus == ReachableViaWiFi || netStatus == ReachableViaWWAN) {
        return YES;
    }else{
        return NO;
    }

}


-(void)setNaviganionImg{
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        UIImage *image = [UIImage imageNamed:@"navigation_bg"];
        [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
        
    }
}

-(void)setNavigationTitle{
    UILabel *lblTitle = [[UILabel alloc] init];
    lblTitle.text = @"Каталог товаров";
    lblTitle.backgroundColor = [UIColor clearColor];
    lblTitle.textColor = [UIColor colorWithRed:242.0/255.0 green:240.0/255.0 blue:234.0/255.0 alpha:1];
    
    lblTitle.font = [UIFont fontWithName:@"American Retro" size:27.0];
    [lblTitle sizeToFit];
    
    self.navigationItem.titleView = lblTitle;
}

@end
